<template>
  <div class="box">
    <header>
      <span class='iconfont ico' @click="() => { this.$router.go(-1) }">&#xe65a;</span>
      <ul>
        <li><span @click="flagList">一号棚 ▼</span>
          <ul class="menu_two" v-show="flag">
            <li>二号温棚</li>
            <li>三号温棚</li>
            <li>四号温棚</li>
            <li>五号温棚</li>
          </ul>
        </li>
      </ul>
    </header>
    <div class="conent">
      <div class="tab">
        <ul>
          <li>
            <p :class="{ temperatures : temperature }" @click="display('temperature')"><img src="./img/temperature/u174.svg" alt=""></p>
            <p>温度</p>
          </li>
          <li>
            <p :class="{ humidity : humidity }" @click="display('humidity')"><img src="./img/temperature/u174.svg" alt=""></p>
            <p>湿度</p>
          </li>
          <li>
            <p :class="{ illumination : illumination }" @click="display('illumination')"><img src="./img/temperature/u174.svg" alt=""></p>
            <p>光度</p>
          </li>
          <li>
            <p :class="{ more : more }" @click="display('more')"><img src="./img/temperature/u174.svg" alt=""></p>
            <p>更多</p>
          </li>
        </ul>
        <div class="tab_conent" v-show="temperature">
          <img src="./img/temperature/u201.svg" class="tem_img" alt="">
          <p class="temperature">{{ this.$store.state.data.tem }}°C</p>
          <div class="tem_slider">
            <!-- <van-slider v-model="value" active-color="#999" inactive-color="rgba(223, 223, 223, 1)"  :min="0" @change="onChange" :max="50" />
            <van-checkbox v-model="checked" shape="square">自动</van-checkbox> -->
            <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="temMin"> - <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="temMax"> <van-button type="primary" size="small" @click="tem">提交</van-button>
          </div>
          <div class="shutDown">
            <img src="./img/temperature/u204.svg" alt="">
          </div>
        </div>
        <div class="tab_conent" v-show="humidity">
          <img src="./img/humidity/u272.svg" class="tem_img" alt="">
          <p class="temperature">{{ this.$store.state.data.hum }}°C</p>
          <div class="tem_slider">
            <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="humMin"> - <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="humMax"> <van-button type="primary" size="small" @click="hum">提交</van-button>
          </div>
          <div class="shutDown">
            <img src="./img/temperature/u204.svg" alt="">
          </div>
        </div>
        <div class="tab_conent" v-show="illumination">
          <img src="./img/illumination/sun.svg" class="tem_img" alt="">
          <p class="temperature">{{ this.$store.state.data.light }}<span>LUX</span></p>
          <div class="tem_slider">
            <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="lightMin"> - <input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="lightMax"> <van-button type="primary" size="small" @click="light">提交</van-button>
          </div>
          <div class="shutDown">
            <img src="./img/temperature/u204.svg" alt="">
          </div>
        </div>
        <div class="tab_conent" v-show="more">
          <img src="./img/temperature/u201.svg" class="tem_img" alt="">
          <p class="temperature">28.2°C</p>
          <div class="tem_slider">
            <van-slider v-model="value" active-color="#999" inactive-color="rgba(223, 223, 223, 1)"  :min="0" @change="onChange" :max="50" />
            <van-checkbox v-model="checked" shape="square">自动</van-checkbox>
          </div>
          <div class="shutDown">
            <img src="./img/temperature/u204.svg" alt="">
          </div>
        </div>
        <div class="tab_footer">
          <span :class="{ temperatures : temperature }" @click="display('temperature')"></span>
          <span :class="{ humidity : humidity }" @click="display('humidity')"></span>
          <span :class="{ illumination : illumination }" @click="display('illumination')"></span>
          <span :class="{ more : more }" @click="display('more')"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Slider, Toast, Checkbox, CheckboxGroup, Button } from 'vant'

Vue.use(Button)
Vue.use(Slider)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
export default {
  data () {
    return {
      value: 36,
      checked: false,
      flag: false,
      temperature: false, // 温度
      humidity: false, // 湿度
      illumination: true, // 光度
      more: false, // 更多
      mqtt: '',
      temMin: '',
      temMax: '',
      humMax: '',
      humMin: '',
      lightMax: '',
      lightMin: ''
    }
  },
  mounted () {
    this.display(this.$route.query.id)
    var reconnectTimeout = 3000;	//连接超时时长
    var host = '49.232.150.163';    // hostname or IP address//MQTT服务器ip地址
    var port = 9001;					//MQTT代理器端口
    var topic = 'Temp';        // 定义订阅主题类型温度
    var topic1 = 'Hum';				// 定义订阅主题类型湿度
    var clientId = 'client-' + Math.ceil(Math.random() * 1000);
    var topic2 = 'Hv';				// 定义订阅主题类型光照强度
    var topic3 = 'Co2';						// 定义订阅主题类型CO2浓度
    var useTLS = false;
    var username = null;
    var password = null;
    //username = "test";
    //password = "123456";
    var cleansession = true;
    var addr = [];
    const MQTTconnect = () => {  
      //连接函数：连接到MQTT代理器
      this.mqtt = new Paho.MQTT.Client(host, port, clientId);
      var options = {
        invocationContext: {
          host: host,
          port: port,
          path: this.mqtt.path,
          clientId: clientId
        },
        timeout: 5,
        useSSL: useTLS,
        cleanSession: cleansession,
        onSuccess: onConnect,
        onFailure: function (message) {
          alert("connect failed..............");//调试语句连接代理器 失败打印
          // $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
          setTimeout(MQTTconnect, reconnectTimeout);
        }
      };

      this.mqtt.onConnectionLost = onConnectionLost;
      this.mqtt.onMessageArrived = onMessageArrived;

      if (username != null) {
        options.userName = username;
        options.password = password;
      }
      this.mqtt.connect(options);
    }

    const onConnect = () =>  {		//连接代理器成功回调函数			
      // Connection succeeded; subscribe to our topic//作为客户端向代理器订阅相关主题
      this.mqtt.subscribe(topic, { qos: 0 });//订阅topic（'Temp'）即温度主题，
    }

    function onConnectionLost(response) {
      setTimeout(MQTTconnect, reconnectTimeout);
      // $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    }

    var onMessageArrived = (message) => {//收到所订阅类型消息回调函数，即只要有人发布自己所订阅的消息类型就会调用此函数
      var topic = message.destinationName;//message.destinationName为消息类型，自己定义变量去接收并且解析
      var payload = message.payloadString;//message.payloadString为消息数据，

      var stra = String(payload)
      
    };
    MQTTconnect();
    axios({
      url: '/api/IntelligentAgriculture/receiveDataController/checkToken',
      method: 'get',
      headers: {'token': localStorage.getItem('token')}
    }).then(res => {
      if (res.data.code === 1001) {
        this.$router.push('/login')
      }
    })
  },

  methods: {
    onChange (value) {
      const vals = '2123'
      const tps = 'news'
      Toast('当前值：' + value)
      // var message = new Paho.MQTT.Message(vals);
    	// message.destinationName = tps;
      // message.qos = 0;
      // console.log(this.mqtt)
    	// this.mqtt.send(message);
      // this.mqtt.publish(tps, 0, vals);
    },
    tem () {
      if (this.temMax !== '' && this.temMin !== '') {
        if (Number(this.temMax) <= 100 && Number(this.temMin) >= 10 && Number(this.temMax) > Number(this.temMin)) {
          const vals = this.temMin + ',' + this.temMax
          const tps = 'setTem'
          var message = new Paho.MQTT.Message(vals);
          message.destinationName = tps;
          message.qos = 0;
          this.mqtt.send(message);
          Toast('发送成功')
          this.mqtt.publish(tps, 0, vals);
        } else {
          Toast('最小值10，最大值100')
        }
      } else {
        Toast('请填写完整')
      }
    },
    hum () {
      if (this.humMax !== '' && this.humMin !== '') {
        if (Number(this.humMax) <= 100 && Number(this.humMin) >= 10 && Number(this.humMax) > Number(this.temMin)) {
          const vals = this.humMin + ',' + this.humMax
          const tps = 'setHum'
          var message = new Paho.MQTT.Message(vals);
          message.destinationName = tps;
          message.qos = 0;
          this.mqtt.send(message);
          Toast('发送成功')
          this.mqtt.publish(tps, 0, vals);
        } else {
          Toast('最小值10，最大值100')
        }
      } else {
        Toast('请填写完整')
      }
    },
    light () {
      if (this.lightMax !== '' && this.lightMin !== '') {
        if (Number(this.lightMax) <= 10000 && Number(this.lightMin) >= 0 && Number(this.lightMax) > Number(this.temMin)) {
          const vals = this.lightMin + ',' + this.lightMax
          const tps = 'setLight'
          var message = new Paho.MQTT.Message(vals);
          message.destinationName = tps;
          message.qos = 0;
          this.mqtt.send(message);
          Toast('发送成功')
          this.mqtt.publish(tps, 0, vals);
        } else {
          Toast('最小值10，最大值100')
        }
      } else {
        Toast('请填写完整')
      }
    },
    flagList () {
      this.flag = !this.flag
    },
    display (fn) {
      if (fn === 'temperature' || fn === '1') {
        this.temperature = true
        this.humidity = false
        this.illumination = false
        this.more = false
      } else if (fn === 'humidity' || fn === '2') {
        this.temperature = false
        this.humidity = true
        this.illumination = false
        this.more = false
      } else if (fn === 'illumination' || fn === '3') {
        this.temperature = false
        this.humidity = false
        this.illumination = true
        this.more = false
      } else if (fn === 'more' || fn === '4') {
        this.temperature = false
        this.humidity = false
        this.illumination = false
        this.more = true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    header {
      display: flex;
      justify-content: space-between;
      padding: 30px 0;
      .ico {
        padding: 0 0 0 20px;
        font-size: 40px;
      }
      ul {
        list-style: none;
        font-size: 34px;
        span {
          font-weight: bolder;
          padding: 0 20px 0 0;
        }
        .menu_two {
          margin-top: 20px;
          border-radius: 20px;
          position:absolute ;
          z-index: 5;
          width: 220px;
          background-color: rgba(227, 227, 227, 1);
          padding: 20px 0 20px 30px;
          right: 10px;
          li {
            line-height: 70px;
            border-bottom: 1px solid #cfcece;
          }
        }
      }
    }
    .conent {
      background-color: rgba(229, 229, 229, 1);
      height: 100%;
      border-radius: 15% 15% 0 0;
      padding: 80px 50px 0 50px;
      .temperatures, .humidity, .illumination, .more {
        background-color: #fff !important;
      }
      .tab {
        ul {
          display: flex;
          font-size: 20px;
          li {
            list-style: none;
            width: 25%;
            p {
              &:nth-of-type(1) {
                display: inline-block;
                overflow: hidden;
                position: relative;
                left: 25%;
                width: 80px;
                height: 80px;
                border-radius: 50%;
                background: #b4b0b0;
                img {
                  width: 30px;
                  height: 40px;
                  position: relative;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%);
                }
              }
              &:nth-of-type(2) {
                text-align: center;
                padding: 10px 0;
              }
            }
          }
        }
        .tab_conent {
          width: 100%;
          background: #fff;
          height: 700px;
          margin: 50px 0 ;
          border-radius: 50px;
          position: relative;
          .tem_img {
            position: relative;
            left: 50%;
            height: 160px;
            transform: translate(-50%, 0);
            margin-top: 70px;
          }
          p {
            span {
              font-size: 40px;
            }
          }
          .shutDown {
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background: #fff;
            box-shadow: 0px 0px 30px #888888;;
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translate(-50%, 50%);
            img {
              position: relative;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -40%);
            }
          }
        }
        .temperature {
          text-align: center;
          font-size: 100px;
          font-weight: bolder;
          margin: 70px 0 80px 0;
        }
        .tem_slider {
          display: flex;
          .van-slider {
            height: 20px;
            width: 65%;
            margin: 0 0 0 50px;
            /deep/.van-slider__button {
              width: 24px;
              border-radius: 35px;
              height: 40px;
              background: #888;
            }
          }
          .van-checkbox{
            margin-left: 25px;
            position:relative;
            top: -10px;
            /deep/.van-checkbox__icon {
              font-size: 20px;
            }
          }
          input {
            width: 30%;
            height: 40px;
            &:nth-of-type(1) {
              margin: 0 10px 0 20px;
            }
            &:nth-of-type(2) {
              margin: 0 20px 0 10px;
            }
          }
        }
        .tab_footer {
          padding: 100px 50px 0 50px;
          span {
            display: inline-block;
            width: 20%;
            height: 15px;
            background: rgba(200, 200, 200, 1);
            margin-right: 6.66%;
            border-radius: 10px;
            &:nth-of-type(4) {
              margin: 0;
            }
          }
        }
      }
    }
  }
</style>
